<template>
  <!-- 总部管理中心/融销直销数据采集 -->
  <div class="collectionData">
    <div class="top_operation">
      <div class="every_operation">
        <span>记账归属：</span>
        <a-range-picker
          v-model="collection"
          :placeholder="['Start Time', 'End Time']"
          style="width: 195px"
          @change="onWeekChange"
          format="YYYY-MM-DD HH:mm:ss"
          :show-time="{
            format: 'HH:mm:ss',
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
          }"
        />
      </div>
      <div class="every_operation">
        <span>创建人：</span>
        <a-input :maxLength="50" placeholder="请输入创建人" v-model="createBy" style="width: 195px" allowClear />
      </div>
      <div class="every_operation">
        <span>创建时间：</span>
        <a-range-picker
          v-model="createTime"
          :show-time="{
            format: 'HH:mm:ss',
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
          }"
          format="YYYY-MM-DD HH:mm:ss"
          :placeholder="['Start Time', 'End Time']"
          @change="createChange"
          @ok="createOk"
          :value="createTime"
          style="width: 195px"
        />
      </div>
      <div class="every_operation">
        <span>修改人：</span>
        <a-input :maxLength="50" placeholder="请输入修改人" v-model="updateBy" style="width: 195px" allowClear />
      </div>
      <div class="every_operation">
        <span>修改时间：</span>
        <a-range-picker
          v-model="updateTime"
          :show-time="{
            format: 'HH:mm:ss',
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
          }"
          format="YYYY-MM-DD HH:mm:ss"
          :placeholder="['Start Time', 'End Time']"
          @change="editChange"
          @ok="editOk"
          :value="updateTime"
          style="width: 195px"
        />
      </div>

      <div class="button_div" style="margin-top: 10px">
        <a-button type="primary" icon="search" @click="onSearch()">搜索</a-button>
        <a-button icon="sync" style="margin-left: 20px" @click="onReset()">重置</a-button>
      </div>
    </div>
    <!-- 下部分 -->
    <div class="bottom_box">
      <div class="button_div">
        <a-button type="primary" @click="onAdd()">新增</a-button>
        <a-button style="margin-left: 20px" @click="onDelete()">删除</a-button>
      </div>
      <div class="select_number">
        <span class="number_span"
          >已选择<b>{{ selectNumber }}</b
          >项</span
        >
        <span class="clear_span" @click="clearSelect">清空</span>
      </div>
      <!-- 右滑抽屉 -->
      <div class="add_btn">
        <!-- :placement="placement" -->
        <a-drawer
          :maskClosable="false"
          :title="drawerTitle"
          :closable="false"
          :visible="visible"
          @close="onClose"
          width="1000"
        >
          <a-form-model
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            labelAlign="left"
          >
            <span style="display: flex; flex-wrap: wrap">
              <a-form-model-item style="width: 50%" ref="financialSalesAmount" prop="financialSalesAmount">
                <span slot="label">
                  <a-popover>
                    <template slot="content">
                      <p style="margin: 0">用户以周为单位进行填写</p>
                    </template>
                    <img src="../../assets/help_yellow.png" alt="" />
                  </a-popover>
                  <span> 融销收入</span>
                </span>
                <a-input-number
                  id="areaNumber"
                  v-model="form.financialSalesAmount"
                  :precision="precision"
                  :min="0"
                  :max="2147483647"
                  style="width: 100%"
                  placeholder="请输入融销收入"
                  @blur="
                    () => {
                      $refs.financialSalesAmount.onFieldBlur()
                    }
                  "
                />
              </a-form-model-item>
              <a-form-model-item style="width: 50%" ref="directSalesAmount" prop="directSalesAmount">
                <span slot="label">
                  <a-popover>
                    <template slot="content">
                      <p style="margin: 0">用户以周为单位进行填写</p>
                    </template>
                    <img src="../../assets/help_yellow.png" alt="" />
                  </a-popover>
                  <span> 直销收入</span>
                </span>

                <a-input-number
                  id="areaNumber"
                  v-model="form.directSalesAmount"
                  :precision="precision"
                  :min="0"
                  :max="2147483647"
                  style="width: 100%"
                  placeholder="请输入直销收入"
                  @blur="
                    () => {
                      $refs.directSalesAmount.onFieldBlur()
                    }
                  "
                />
              </a-form-model-item>
              <a-form-model-item style="width: 50%" ref="billTime" prop="billTime">
                <span slot="label">
                  <a-popover>
                    <template slot="content">
                      <p style="margin: 0">
                        记账归属系统自动取当前一周的时间即开始时间取周六的00：00：00，结束时间取下一周周五的23：59：59
                      </p>
                    </template>
                    <img src="../../assets/help_yellow.png" alt="" />
                  </a-popover>
                  <span> 记账归属</span>
                </span>
                <!-- :show-time="{
                format: 'HH:mm:ss',
                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
              }" -->
                <a-range-picker
                  v-model="form.billTime"
                  disabled
                  format="YYYY-MM-DD"
                  :placeholder="['Start Time', 'End Time']"
                  style="width: 100%"
                  :value="form.billTime"
                  @blur="
                    () => {
                      $refs.billTime.onFieldBlur()
                    }
                  "
                />
              </a-form-model-item>
            </span>

            <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button type="primary" @click="onSubmit"> 确定 </a-button>
              <a-button
                style="margin-left: 10px"
                @click="
                  () => {
                    visible = false
                  }
                "
              >
                取消
              </a-button>
            </a-form-model-item>
          </a-form-model>
        </a-drawer>
      </div>
      <!-- 表格 -->
      <div class="data_source_list">
        <div class="data_source_details">
          <a-table
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :loading="tableLoading"
            :columns="columns"
            :data-source="data"
            :pagination="false"
            bordered
            rowKey="id"
          >
            <span slot="billTime" slot-scope="text, record">
              <span>{{ `${record.billTimeBegin}-${record.billTimeEnd}` }}</span>
            </span>
            <!-- :scroll="xScroll" -->
            <a slot="action" slot-scope="text, record" href="javascript:;">
              <span style="margin-right: 8px" v-if="setBtn(record)" @click="editDrawer(record)">修改</span>
              <span style="margin-right: 8px; color: #c2c2c2; cursor: no-drop" v-else @click="(e) => e.preventDefault()"
                >修改</span
              >
              <span @click="delDrawer(record)">删除</span>
            </a>
          </a-table>
          <!-- 底部分页组件 -->
          <BottomPagination :total="total" @pageChange="pageChange" @sizeChange="sizeChange"></BottomPagination>
        </div>
        <!-- 删除对话框 -->
        <DelModal v-model="batchDeleteVisible"
          :loading="batchDeleteConfirmLoading"
          @ok="batchDeleteHandleOk"
          @cancel="batchDeleteHandleCancel" />
      </div>
    </div>
  </div>
</template>
<script>
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    ellipsis: true,
    width: '80px',
    customRender: (taxe, records, index) => `${index + 1}`,
  },
  {
    title: '融销收入',
    dataIndex: 'financialSalesAmount',
    key: 'financialSalesAmount',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '直销收入',
    dataIndex: 'directSalesAmount',
    key: 'directSalesAmount',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '记账归属',
    align: 'center',
    scopedSlots: {
      customRender: 'billTime',
    },
    ellipsis: true,
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    key: 'createBy',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '修改人',
    dataIndex: 'updateBy',
    key: 'updateBy',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    scopedSlots: {
      customRender: 'action',
    },
    align: 'center',
    width: '120px',
  },
  // fixed: 'right',
]
import { getDate, setBtn } from '../../utils/getDate'
import { getSaleList, createSale, editSale, delSale } from '@api/api'
import moment from 'moment' //导入文件
import BottomPagination from '../meter/BottomPagination'
import DelModal from '@comp/base/delModal'
export default {
  name: 'CollectionData',
  data() {
    return {
      collection: null,
      collectionStartTime: '',
      collectionEndTime: '',
      createBy: null, //创建人
      createTime: [],
      createTime_begin: '',
      createTime_end: '',
      updateBy: null, //修改人
      updateTime: [],
      updateTime_begin: '',
      updateTime_end: '',
      columns,
      selectNumber: 0,
      selectedRowKeys: [],
      xScroll: {
        x: 2110,
      },
      labelCol: { span: 7 },
      wrapperCol: { span: 16 },
      drawerTitle: null,
      visible: false,
      precision: 2,

      form: {
        financialSalesAmount: '',
        directSalesAmount: '',
        billTime: [],
      },
      id: null,
      billTimeBegin: null,
      billTimeEnd: null,
      rules: {
        //表单验证规则
        financialSalesAmount: [{ required: true, message: '请输入融销收入', trigger: 'blur' }],
        directSalesAmount: [{ required: true, message: '请输入直销收入', trigger: 'blur' }],
        billTime: [{ required: true, message: '请输入记账归属', trigger: 'blur' }],
      },

      validStatus: true,
      addMode: true, //判断条件新增或修改
      ids: null,
      modalTitle: '批量删除',
      data: [],
      tableLoading: false, //表格加载动画状态
      pageNo: 1,
      pageSize: 10,
      total: 0,
      batchDeleteVisible: false,
      batchDeleteConfirmLoading: false,
    }
  },
  components: {
    BottomPagination,
    DelModal,
  },
  methods: {
    getDate,
    setBtn,
    moment,
    getDataList() {
      // collection: this.collection,
      let params = {
        billTimeBegin: this.collectionStartTime,
        billTimeEnd: this.collectionEndTime,
        createBy: this.createBy,
        createTime_begin: this.createTime_begin,
        createTime_end: this.createTime_end,
        updateBy: this.updateBy,
        updateTime_begin: this.updateTime_begin,
        updateTime_end: this.updateTime_end,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        delFlag: 0,
      }
      this.tableLoading = true
      getSaleList(params).then((res) => {
        if (res.success) {
          this.data = res.result.records
          this.total = res.result.total
          this.tableLoading = false
        }
      })
    },
    onWeekChange(e, date) {
      this.collection = e
      this.collectionStartTime = date[0]
      this.collectionEndTime = date[1]
    },
    //
    createOk(e) {
      console.log('createOk', e)
    },
    // 创建时间监听
    createChange(e, date) {
      this.createTime = e
      this.createTime_begin = date[0]
      this.createTime_end = date[1]
    },
    // onClose
    onClose(e) {
      this.visible = false
    },
    //
    editOk(e) {
      console.log('editOk', e)
    },
    // 修改时间监听
    editChange(e, date) {
      this.updateTime = e
      this.updateTime_begin = date[0]
      this.updateTime_end = date[1]
    },
    // 搜索
    onSearch() {
      this.getDataList()
    },
    //重置
    onReset() {
      this.collection = []
      this.collectionStartTime = ''
      this.collectionEndTime = ''
      this.createBy = ''
      this.data = []
      this.pageSize = 10
      this.pageNo = 1
      this.total = 0
      this.createTime = []
      this.createTime_begin = ''
      this.createTime_end = ''
      this.updateBy = null
      this.updateTime = []
      this.updateTime_begin = ''
      this.updateTime_end = ''
      this.selectNumber = 0
      this.selectedRowKeys = []
      this.tableLoading = true
      setTimeout(() => {
        this.tableLoading = false
      }, 100)
    },
    // 新增
    onAdd() {
      this.drawerTitle = '创建融销直销数据'
      this.addMode = true
      this.visible = true

      // 只有验证失败，新增的时候才重置验证状态
      if (this.validStatus === false) {
        this.$refs.ruleForm.resetFields()
      }
      this.form.financialSalesAmount = ''
      this.form.directSalesAmount = ''
      try {
        let time = getDate()
        let format = 'YYYY-MM-DD HH:mm:ss'
        this.form.billTime = [moment(time[0], format), moment(time[1], format)]
        this.billTimeBegin = time[0]
        this.billTimeEnd = time[1]
      } catch {}
    },
    // 删除按钮
    onDelete() {
      if (this.selectedRowKeys.length) {
        this.modalTitle = '批量删除'
        this.batchDeleteVisible = true
        this.ids = this.selectedRowKeys.join(',')
      } else {
        this.$message.warning('请先勾选需要删除的项！')
      }
    },
    // 表单提交
    onSubmit() {
      // 根据接口返回展示提示信息
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.validStatus = true
          if (this.addMode) {
            let params = {
              financialSalesAmount: this.form.financialSalesAmount,
              directSalesAmount: this.form.directSalesAmount,
              billTimeBegin: this.billTimeBegin,
              billTimeEnd: this.billTimeEnd,
            }
            // 新增
            createSale(params).then((res) => {
              if (res.success) {
                this.getDataList()
                this.visible = false
                this.$message.warning('保存成功！')
              } else {
                this.$message.warning(res.message)
              }
            })
          } else {
            // 修改逻辑
            let params = {
              id: this.id,
              financialSalesAmount: this.form.financialSalesAmount,
              directSalesAmount: this.form.directSalesAmount,
              billTimeBegin: this.billTimeBegin,
              billTimeEnd: this.billTimeEnd,
            }
            editSale(params).then((res) => {
              if (res.success) {
                this.getDataList()
                this.visible = false
                this.$message.warning('保存成功！')
              } else {
                this.$message.warning(res.message)
              }
            })
          }
        } else {
          this.validStatus = false
          return false
        }
      })
    },
    // 清空选中
    clearSelect() {
      this.selectNumber = 0
      this.selectedRowKeys = []
    },
    //修改item数据
    editDrawer(record) {
      this.drawerTitle = '修改融销直销数据'
      this.visible = true
      this.addMode = false
      this.id = record.id
      this.form.financialSalesAmount = record.financialSalesAmount
      this.form.directSalesAmount = record.directSalesAmount
      this.billTimeBegin = record.billTimeBegin
      this.billTimeEnd = record.billTimeEnd
      this.form.billTime = [
        this.moment(`${record.billTimeBegin + ' 00:00:00'}`, 'YYYY-MM-DD HH:mm:ss'),
        this.moment(`${record.billTimeEnd + ' 23:59:59'}`, 'YYYY-MM-DD HH:mm:ss'),
      ]
      // 只有验证失败，新增的时候才重置验证状态
      if (this.validStatus === false) {
        this.$refs.ruleForm.resetFields()
      }
      // this.form.billTime = [
      //   this.moment(record.billTimeBegin).format('YYYY-MM-DD') + ' 00:00:00',
      //   this.moment(record.billTimeEnd).format('YYYY-MM-DD') + ' 23:59:59',
      // ]
      // this.form.
      // this.$nextTick(() => {
      //   this.$refs.ruleForm.resetFields()
      // })
      //   this.form = e.
    },
    // 删除item数据
    delDrawer(e) {
      this.modalTitle = '删除'
      this.batchDeleteVisible = true
      this.ids = e.id
    },
    //监听选中条数
    onSelectChange(e) {
      this.selectedRowKeys = e
      this.selectNumber = e.length
      // if (this.selectedRowKeys.length > 0) {
      //   this.deletdBtnShow = true
      // } else {
      //   this.deletdBtnShow = false
      // }
    },
    // 批量删除确定
    batchDeleteHandleOk(e) {
      this.batchDeleteConfirmLoading = true
      let params = {
        ids: this.ids,
      }
      delSale(params).then((res) => {
        if (res.success) {
          this.batchDeleteVisible = false
          this.batchDeleteConfirmLoading = false
          this.selectNumber = 0
          this.selectedRowKeys = []
          // this.deletdBtnShow = false
          this.getDataList()
          this.$message.warning(res.message)
        }
      })
    },
    // 批量删除取消
    batchDeleteHandleCancel(e) {
      this.batchDeleteVisible = false
    },
    // 获取当前页数、条数
    pageChange(data1, data2) {
      this.pageNo = data1
      this.pageSize = data2
      this.getDataList()
    },
    // 获取当前页数、条数
    sizeChange(data1, data2) {
      this.pageNo = data1
      this.pageSize = data2
      this.getDataList()
    },
  },
}
</script>
<style lang="less" scoped>
.collectionData {
  width: 100%;
  box-sizing: border-box;
  .top_operation {
    background: #ffffff;
    padding: 0 10px 10px 10px;
    font-style: Microsoft YaHei;
    margin-bottom: 10px;
    overflow: hidden;
    .every_operation {
      float: left;
      margin-top: 10px;
      margin-right: 20px;
      span {
        display: inline-block;
        width: 85px;
      }
    }
    .button_div {
      float: left;
    }
  }
  .bottom_box {
    padding: 10px 10px 10px 10px;
    font-style: Microsoft YaHei;
    background: #ffffff;
    .button_div {
      margin-bottom: 10px;
    }
    .select_number {
      width: 100%;
      height: 36px;
      padding-left: 20px;
      margin-bottom: 10px;
      box-sizing: border-box;
      background: rgba(57, 72, 103, 0.22);
      line-height: 36px;
      .number_span {
        color: #ffffff;
        margin-right: 30px;
        b {
          color: #394867;
          margin: 0 15px;
        }
      }
      .clear_span {
        cursor: pointer;
        color: #394867;
      }
    }
    .add_btn {
      margin-bottom: 10px;
    }
    .data_source_list {
      h3 {
        font-weight: bold;
      }
      .data_pagination {
        width: 100%;
        height: 32px;
        margin: 20px 0 10px 0;
      }
    }
  }
}
</style>